package zouran.shounewsspringboot.service.serviceImp;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zouran.shounewsspringboot.entity.Identity;
import zouran.shounewsspringboot.entity.MyConfig;
import zouran.shounewsspringboot.entity.News;
import zouran.shounewsspringboot.mapper.IdentityMapper;
import zouran.shounewsspringboot.mapper.NewsMapper;
import zouran.shounewsspringboot.service.NewsService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @author zouran
 * createDate：2023/5/31  17:32
 */
@Service
public class NewsServiceImp implements NewsService {
    private final NewsMapper newsMapper;
    private final IdentityMapper identityMapper;
    private final MyConfig myConfig;
    public NewsServiceImp(NewsMapper newsMapper, IdentityMapper identityMapper, MyConfig myConfig) {
        this.newsMapper = newsMapper;

        this.identityMapper = identityMapper;
        this.myConfig = myConfig;
    }

    @Override
    public List<News> getAllNewsByAuthor(String author) {
        return newsMapper.getAllNewsByAuthor(author);
    }

    @Override
    @Transactional
    public boolean addWechatNews(String url) throws IOException {
        String title=null,img = null,author=null;
        LocalDateTime localDateTime = null;
            CloseableHttpClient httpClient= HttpClients.createDefault();
            HttpGet httpGet=new HttpGet();
            httpGet.setURI(URI.create(url));
            CloseableHttpResponse response= httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode()==200){
                String html= EntityUtils.toString(response.getEntity());
                Document document= Jsoup.parse(html);
                Elements titles = document.getElementsByAttributeValue("property","og:title");
                title=titles.get(0).attr("content");
                Elements imgs = document.getElementsByAttributeValue("property", "og:image");
                img=save(imgs.get(0).attr("content"));
                author=Objects.requireNonNull(document.getElementById("js_name")).text();
                Elements scripts=document.select("script");
                for (Element script : scripts) {
                    String html1=script.html();
                    if(html1.contains("document.getElementById(\"publish_time\")")){
                        String[] strings=html1.split("\"");
                        Date date=new Date(Long.parseLong(strings[13]+"000"));
                        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        DateTimeFormatter timeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        localDateTime=LocalDateTime.parse(formatter.format(date),timeFormatter);
                    }
                }
            }
            News news=new News(null,img,title,author,localDateTime,url);
            if(identityMapper.judgeAuthorExist(author)==null){
                Identity identity=new Identity(author,"wechat");
                identityMapper.insert(identity);
            }
            newsMapper.insert(news);
        return true;
    }

    @Override
    public int getAllCount() {
        return newsMapper.selectCount(null);
    }

    /**
     * @param url 图片下载链接
     * @return 图片存储的相对位置
     */
    private String save(String url) {
        String fileName= UUID.randomUUID()+".png";
        try {
            URL url1 = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            if (connection.getResponseCode() == 200) {
                InputStream inputStream = connection.getInputStream();
                String store= myConfig.getFilePath();
                if(!new File(store).exists()&&!new File(store).mkdirs())
                    return null;
                FileOutputStream outputStream = new FileOutputStream(store+fileName);
                byte[] bytes = new byte[1024];
                int len;
                while ((len = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
                inputStream.close();
                outputStream.close();
                connection.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return fileName;
    }
}
